const { readFile, writeFile } = require('./file')
const moment = require('moment');
const { RESULT } = require('../config/index')

// 修改表名
const updateCollection = (body, cb) => {
  const { tableValue, tableName } = body;
  readFile('t_object', (res) => {
    res.forEach(item => {
      if (item.tableValue === tableValue) {
        item.tableName = tableName;
        item.utime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")//更新时间
      }
    })
    writeFile('t_object', res, (err) => {
      if (err) {
        RESULT.status = 501
        RESULT.message = '修改失败'
      }
      cb(RESULT)
    })
  })
}
// 修改数据
const updateDataToCollection = (tableName, body, cb) => {
  readFile(tableName, (res) => {
    body.utime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")//更新时间
    let i=res.findIndex(item=>item._id===body._id)
    res.splice(i,1,body)
    writeFile(tableName, res, (err) => {
      if (err) {
        RESULT.status = 501
        RESULT.message = '修改失败'
      }
      cb(RESULT)
    })
  })
}

exports.updateCollection = updateCollection
exports.updateDataToCollection = updateDataToCollection